package club.adger.server.service.impl;

import club.adger.server.dto.SectionDto;
import club.adger.server.dto.PageDto;
import club.adger.server.entity.Section;
import club.adger.server.entity.SectionExample;
import club.adger.server.mapper.SectionMapper;
import club.adger.server.service.SectionService;
import club.adger.server.utils.CopyUtil;
import club.adger.server.utils.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
        import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: Adger
 * @Date: 2020/07/25/5:23
 */
@Service
public class SectionServiceImpl implements SectionService {
    @Resource
    private SectionMapper sectionMapper;

    /**
     * PageDto 是分页数据传输的 实体类对象
     * @param pageDto
     * @return
     */
    public void list(PageDto pageDto){
        SectionExample sectionExample = new SectionExample();
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        List<Section> sectionsList = sectionMapper.selectByExample(null);
        sectionExample.setOrderByClause("sort asc");
        PageInfo<Section> sectionPageInfo = new PageInfo<>(sectionsList);
        pageDto.setTotal(sectionPageInfo.getTotal());
        List<SectionDto> sectionDtoList = CopyUtil.copyList(sectionsList, SectionDto.class);
        pageDto.setList(sectionDtoList);
    }

    /**
     * 这是新增或者修改的方法 下面 private 这里是公开的方法 调用就这个方法 不管内部怎么实现的
     * @param sectionDto
     */
    public void add(SectionDto sectionDto){
        Section section = CopyUtil.copy(sectionDto, Section.class);
        if(StringUtils.isEmpty(sectionDto.getId())){
            this.insert(section);
        }else{
            this.update(section);
        }
    }

    /**
     * 这里都是private
     * 这是添加的方法
     * @param section
     */
    private void insert(Section section){
    Date now = new Date();
            section.setCreatedAt(now);
            section.setUpdatedAt(now);
        section.setId(UuidUtil.getShortUuid());
        sectionMapper.insert(section);
    }

    /**
     * 这里也是private 这是修改的方法
     * @param section
     */
    private void update(Section section){
            section.setUpdatedAt(new Date());
        sectionMapper.updateByPrimaryKey(section);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        sectionMapper.deleteByPrimaryKey(id);
    }
}
